<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
  </head>
  <body>
    <!-- 用于收集输入内容 -->
    <input type="text" placeholder="请输入需要发送的内容" />
    <!-- 用于发送websocket请求 -->
    <button>websocket测试</button>
    <!-- 用于显示websock服务器的响应 -->
    <div class="show"></div>
    <script src="/socket.io/socket.io.js"></script>
    <script>
      var input = document.querySelector('input')
      var button = document.querySelector('button')
      var div = document.querySelector('div')
      var socket = io('http://localhost:3000')
      button.addEventListener('click', function() {
        socket.emit('msg', input.value)
        input.value = ''
      })

      socket.on('server', function(data) {
        var dv = document.createElement('div')
        dv.innerHTML = data.msg + '----' + data.date
        if (data.type === 0) {
          dv.style.color = 'green'
        }
        if (data.type === 1) {
          dv.style.color = 'red'
        }
        if (data.type === 2) {
          dv.style.color = 'gray'
        }
        div.appendChild(dv)
      })
    </script>
  </body>
</html>
